/**
 * Created by cchen on 2015/4/16.
 */
var sharesService = require('../../services/mobile/sharesService');
var messageUtil = require('../../common/utils/messageUtil');
var toolUtil = require('../../common/utils/toolUtil');
var cacheUtil = require('../../common/utils/cacheUtil');

var typeName = {
    qst: "question",
    act: "activity",
    top: "specialTopic",
    app: "app"

};

errorHandler = function (msg, err, req, res) {
    logger.error('Share controller ' + msg + '  - - ' + err.message);
    res.json(messageUtil.composeFailedMessage(req, '无法分享'));
};

queryShareURL = function (req, res, userId, feedsId, targetApp, feedsType) {
    var isExistCallback = function (err, shareObj) {
        if (err) {
            errorHandler("GET  URL Callback", err, req, res);
            return
        }
        if (!shareObj) {
            shareObj = sharesService.addNewShare(userId, feedsId, targetApp, feedsType);
        }
        var url = sharesService.urlGenerate(shareObj);
        res.json(messageUtil.composeSucceededMessage(req, null, {"url": url}));

    };
    sharesService.shareIsExisted(userId, feedsId, targetApp, feedsType, isExistCallback);
};

onError = function (msg, err, req, res) {
    logger.error('Service As User controller ' + msg + '  - - ' + err.message ? err.message : 'error');
    res.json(messageUtil.composeFailedMessage(req, err.message));
};

onSuccess = function (data, req, res) {
    res.json(messageUtil.composeSucceededMessage(req, null, data));
};

onResponse = function (err, data, req, res) {
    if (err) {
        onError(err.message, err, req, res);
    } else {
        onSuccess(data, req, res);
    }
};
exports.shareApp = function (req, res) {
    sharesService.shareApp(req.params.userId, req.params.targetApp, function (err, obj) {
        onResponse(err, obj, req, res);
    });
};

exports.shareSpectialTopic = function (req, res) {
    sharesService.shareSpectialTopic(req.params.userId, req.params.targetApp, req.params.topicId, function (err, obj) {
        onResponse(err, obj, req, res);
    });
};

exports.shareActivity = function (req, res) {
    sharesService.shareActivity(req.params.userId, req.params.targetApp, req.params.activityId, function (err, obj) {
        onResponse(err, obj, req, res);
    });
};

exports.shareQuestion = function (req, res) {
    sharesService.shareQuestion(req.params.userId, req.params.targetApp, req.params.questionId, function (err, obj) {
        onResponse(err, obj, req, res);
    });
};


exports.getSharedFeeds = function (req, res) {


    sharesService.getSharedFeeds(req.params.shareId, req.params.userId, req.cparams, function (err, obj) {
        onResponse(err, obj, req, res);
    });
};

exports.getAppUserShare = function (req, res) {
    var userId = req.params.userId;

    sharesService.getAppUserShareService(userId, req.cparams, function (err, result) {
        onResponse(err, result, req, res);
    })
};

exports.getPartakesByActivityId = function (req, res) {
    sharesService.getPartakesByActivityId(req.params.pageNo, req.params.activityId, function (err, result) {
        onResponse(err, result, req, res);
    })
};

exports.getActivityMessageCode = function (req, res) {
    var phone = req.params.phone;

    var key = 'activity:messageCode:' + phone;

    var message = {
        "mobilePhone": phone,
        "verificationCode": toolUtil.generateVerificationCode(phone, key)
    };
    logger.info(message);
    toolUtil.putMessageVerificationCodeMQ(message);
    res.json(messageUtil.composeSucceededMessage(req, null, null))
};

exports.joinInActivityByWechat = function (req, res) {

    var input = req.body;
    logger.info(input);
    var key = 'activity:messageCode:' + input.phone;

    cacheUtil.cacheGet(key, function (err, code) {
        if (code == null || code != input.messageCode) {
            res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '验证码错误'}));
        } else {
            var data = {
                number: input.number,
                note: input.note,
                name: input.name,
                phone: input.phone,
                address: input.address,
                partakeType: 2
            };

            sharesService.joinInActivityByWechatService(input.activityId, data, function (err, result) {
                if (err) {
                    res.json(messageUtil.composeErrorMessage(req, err));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null))
                }
            })
        }
    })
};

exports.shareCallback = function (req, res) {
    var input = req.body;
    input.os = req.query.type;

    sharesService.shareCallbackService(input, function (err, result) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, null))
        } else {

            if (input.feedsType == 'question') {
                toolUtil.putMessageSmartRankMQ({questionId: input.feedsId, type: 4});
            }

            var action = 17;
            if (result) {
                action = 41;
            } else {
                if (input.feedsId == '568493aef88c8b3a5340a9f2') {
                    action = 42;
                }
            }


            toolUtil.hessianManualAddScore(input.userId, action, null, null, function (value) {
                if (value != null && value.currentValue != null && value.currentValue != 0) {
                    res.json(messageUtil.composeSucceededMessage(req, "分享成功", null));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, "分享成功", null));
                }
            });
        }
    })
};
/*  宝宝树66小区二次改造    add   luolh  20170726   start   */
exports.shareBefore = function (req, res) {
    var input = req.body;
    sharesService.shareBeforeService(input.url, function (err, result) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, null))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result))
        }
    })
};
/*  宝宝树66小区二次改造    add   luolh  20170726   end   */

exports.addQrcodeStatistic = function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    var input = req.body;
    sharesService.addQrcodeStatistic(input, function (err) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, null))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null))
        }
    })
};
/*  宝宝树66小区三期改造    add  接受邀请优化 luolh  20170930   start   */
// 初期旧分享访问处理-跳转到新处理页面
exports.addInvitationShareOldInit = function(req, res) {
// 旧有跳转到新跳转方式
    res.redirect("app/inviteReward/index.html/"+req.param("userObjId")
        +"/"+req.param("inviteCode")
        +"/"+req.param("userId")
        +"/"+req.param("feedsType")
        +"/"+req.param("uuid")
        +"/"+req.param("from")
    +"/");
}
// 初期分享页面新处理
exports.addInvitationShareInit = function(req, res) {
    var url ="";
    restClient.get("http://66xiaoqu.babytreeimg.com/app/json/download_1023.json", function (data, response) {
        //logger.info(data);
        // var res = eval("(" + data + ")");
        var u = req.header("user-agent");
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        var ua = u.toLowerCase();
        var isWx = ua.match(/MicroMessenger/i) === "micromessenger";
        var url = "#";
        var os = "";
        if (isAndroid) {
            url = data.android.default;
            os = "Android";
            // $("div.device_text span").css("font-size", "16px");
            if (isWx) {
                // $('footer').show();
                url = data.android.wx;
                os = "Android";
            }
        }
        else if (isiOS) {
            url = data.android.default;
            os = "iOS";
            if (isWx) {
                // $('footer').show();
                url = data.android.default;
                os = "iOS";
            }
        }
        var userId = req.param("userObjId");
        var uuid = req.param("uuid");
        var feedsType = req.param("feedsType");
        var reqcparams = {
            userId : userId,
            uuid : uuid,
            feedsType : feedsType
        }

        sharesService.getAppUserShareService(userId, reqcparams, function (err, result) {
            console.log("result:" + result);
            res.render('appInvitation',
                {
                    userObjId:req.param("userObjId"),
                    inviteCode:req.param("inviteCode"),
                    userId:req.param("userId"),
                    feedsType:req.param("feedsType"),
                    uuid:req.param("uuid"),
                    from:req.param("from"),
                    urlUpload : url,
                    message : req.param("message"),
                    nickname:result.nickName,
                    images : (result.images == null || result.images == "")  ? "http://66xiaoqu.babytreeimg.com/20170928/img/portrait_normal.jpg":result.images,
                    communityName: result.communityName,
                    invitationCode: result.invitationCode,
                    communityId: result.communityId
                }
            ); // 调用当前路径下的 test.jade 模板
        });
    }).on('error', function (err) {
        logger.error('sendMessageByCustomService' + err.message);
    });
}

// post分享邀请提交电话号码处理
exports.addInvitationShareNew = function (req, res) {

    var phone = req.body.phone;
    var message = "";
    var userId = req.param("userObjId");
    var uuid = req.param("uuid");
    var feedsType = req.param("feedsType");
    var reqcparams = {
        userId : userId,
        uuid : uuid,
        feedsType : feedsType
    }
    sharesService.getAppUserShareService(userId, reqcparams, function (err, result) {
        console.log("result:" + result);
        if (phone == null || phone == "") {
            message = "请填写手机号码";
            res.render('appInvitation',
                {
                    userObjId:req.param("userObjId"),
                    inviteCode:req.param("inviteCode"),
                    userId:req.param("userId"),
                    feedsType:req.param("feedsType"),
                    uuid:req.param("uuid"),
                    from:req.param("from"),
                    urlUpload : url,
                    message : message,
                    nickname:result.nickName,
                    images : (result.images == null || result.images == "")  ? "http://66xiaoqu.babytreeimg.com/20170928/img/portrait_normal.jpg":result.images,
                    communityName: result.communityName,
                    invitationCode: result.invitationCode,
                    communityId: result.communityId
                }
            ); // 调用当前路径下的 test.jade 模板
            // res.redirect("inviteReward/index.html?userObjId="+req.param("userObjId")
            //     +"&inviteCode="+req.param("inviteCode")
            //     +"&userId="+req.param("userId")
            //     +"&feedsType="+req.param("feedsType")
            //     +"&uuid="+req.param("uuid")
            //     +"&from="+req.param("from")
            //     +"&message="+message);
        } else if (!/^[1][3-9][0-9]{9,9}$/.test(phone)) {
            message = "请填写正确的手机号码";
            res.render('appInvitation',
                {
                    userObjId:req.param("userObjId"),
                    inviteCode:req.param("inviteCode"),
                    userId:req.param("userId"),
                    feedsType:req.param("feedsType"),
                    uuid:req.param("uuid"),
                    from:req.param("from"),
                    urlUpload : url,
                    message : message,
                    nickname:result.nickName,
                    images : (result.images == null || result.images == "")  ? "http://66xiaoqu.babytreeimg.com/20170928/img/portrait_normal.jpg":result.images,
                    communityName: result.communityName,
                    invitationCode: result.invitationCode,
                    communityId: result.communityId
                }
            ); // 调用当前路径下的 test.jade 模板
            // res.redirect("inviteReward/index.html?userObjId="+req.param("userObjId")
            //     +"&inviteCode="+req.param("inviteCode")
            //     +"&userId="+req.param("userId")
            //     +"&feedsType="+req.param("feedsType")
            //     +"&uuid="+req.param("uuid")
            //     +"&from="+req.param("from")
            //     +"&message="+message);
        } else {
            var url ="";
            restClient.get("http://66xiaoqu.babytreeimg.com/app/json/download_1023.json", function (data, response) {
                logger.info(data);
                // var res = eval("(" + data + ")");
                var u = req.header("user-agent");
                var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android�ն˻���uc�����
                var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios�ն�
                var ua = u.toLowerCase();
                var isWx = ua.match(/MicroMessenger/i) === "micromessenger";
                var url = "#";
                var os = "";
                if (isAndroid) {
                    url = data.android.default;
                    os = "Android";
                    // $("div.device_text span").css("font-size", "16px");
                    if (isWx) {
                        // $('footer').show();
                        url = data.android.wx;
                        os = "Android";
                    }
                }
                else if (isiOS) {
                    url = data.android.default;
                    os = "iOS";
                    if (isWx) {
                        // $('footer').show();
                        url = data.android.default;
                        os = "iOS";
                    }
                }
                var input = req.body;

                sharesService.addInvitationShare(input, function (err, result) {
                    if (err) {
                        message = "网络异常";
                        res.render('appInvitation',
                            {
                                userObjId:req.param("userObjId"),
                                inviteCode:req.param("inviteCode"),
                                userId:req.param("userId"),
                                feedsType:req.param("feedsType"),
                                uuid:req.param("uuid"),
                                from:req.param("from"),
                                urlUpload : url,
                                message : message,
                                nickname:result.nickName,
                                images : (result.images == null || result.images == "")  ? "http://66xiaoqu.babytreeimg.com/20170928/img/portrait_normal.jpg":result.images,
                                communityName: result.communityName,
                                invitationCode: result.invitationCode,
                                communityId: result.communityId
                            }
                        ); // 调用当前路径下的 test.jade 模板
                        // res.redirect("inviteReward/index.html?userObjId="+req.param("userObjId")
                        //     +"&inviteCode="+req.param("inviteCode")
                        //     +"&userId="+req.param("userId")
                        //     +"&feedsType="+req.param("feedsType")
                        //     +"&uuid="+req.param("uuid")
                        //     +"&from="+req.param("from")
                        //     +"&message="+message);
                    } else if(result == 2) {
                        message = "该手机号已被注册";
                        res.render('appInvitation',
                            {
                                userObjId:req.param("userObjId"),
                                inviteCode:req.param("inviteCode"),
                                userId:req.param("userId"),
                                feedsType:req.param("feedsType"),
                                uuid:req.param("uuid"),
                                from:req.param("from"),
                                urlUpload : url,
                                message : message,
                                nickname:result.nickName,
                                images : (result.images == null || result.images == "")  ? "http://66xiaoqu.babytreeimg.com/20170928/img/portrait_normal.jpg":result.images,
                                communityName: result.communityName,
                                invitationCode: result.invitationCode,
                                communityId: result.communityId
                            }
                        ); // 调用当前路径下的 test.jade 模板
                        // res.redirect("inviteReward/index.html?userObjId="+req.param("userObjId")
                        //     +"&inviteCode="+req.param("inviteCode")
                        //     +"&userId="+req.param("userId")
                        //     +"&feedsType="+req.param("feedsType")
                        //     +"&uuid="+req.param("uuid")
                        //     +"&from="+req.param("from")
                        //     +"&message="+message);
                    } else {
                        res.render('appUpload',
                            {uploadUrl : url}
                        ); // 调用当前路径下的 test.jade 模板
                    }
                })
            }).on('error', function (err) {
                logger.error('sendMessageByCustomService' + err.message);
            });
        }
    });

};
// 分享链接-下载应用页面
exports.addInvitationShareAppUpload = function (req, res) {
    res.render('appUpload',
        {uploadUrl : req.param("uploadUrl")}
    ); // 调用当前路径下的 test.jade 模板
}
/*  宝宝树66小区三期改造    add  接受邀请优化 luolh  20170930   end   */

exports.addInvitationShare = function (req, res) {
    var input = req.body;

    sharesService.addInvitationShare(input, function (err, result) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, null))
        } else {
            var result = {
                "result": {
                    "status": result,
                    "message": "ok"
                }
            };
            res.json(result);
        }
    })
};

exports.getCommunityReward = function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    var input = req.body;
    sharesService.getCommunityReward(input, function (err, result) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, null))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result))
        }
    })
};

exports.getSharePageGoods = function (req, res) {
    sharesService.getSharePageGoods(function (err, result) {
        if (err) {
            logger.error('Failed to getRepliesByGoodsId...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7010));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7010));
        }
    });
};

exports.getGoodsDetail = function (req, res) {
    var goodsId = req.params.goodsId;

    sharesService.getGoodsDetail(goodsId, function (err, result) {
        if (err) {
            logger.error('Failed to getGoodsDetail...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7007));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7007));
        }
    });
};

exports.getCommunityActivity = function (req, res) {
    var input = req.params;
    var activityId = req.params.activityId;

    sharesService.getCommunityActivity(activityId, input, function (err, result) {
        if (err) {
            logger.error('Failed to getCommunityActivity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3023));
        } else {
            logger.info(result);
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3023));
        }
    });
};

exports.getShareRestfulByCondition = function (req, res) {
    var input = req.params;

    sharesService.getShareRestfulByCondition(input, function (err, result) {
        if (err) {
            logger.error('Failed to getShareRestfulByCondition... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3024));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3024));
        }
    });
};

exports.getShareContentByKey = function (req, res) {

    var input = req.params;

    sharesService.getShareContentByKey(input, function (err, result) {
        if (err) {
            logger.error('Failed to getShareContentByKey... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3025));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 3025));
        }
    });

};

exports.getTopic = function (req, res) {
    var input = req.params;

    sharesService.getTopic(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get getTopic ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4023));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 4023));
        }
    })
};

exports.getShareByTopicId = function (req, res) {
    var input = req.params;

    sharesService.getShareByTopicId(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get getShareByTopicId ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4024));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 4024));
        }
    })
};